<template>
  <div class="permission-config">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>权限配置</h1>
      <p>管理角色权限和访问控制</p>
    </div>

    <!-- 权限配置选项卡 -->
    <el-tabs v-model="activeTab" type="border-card" class="permission-tabs">
      <!-- 角色管理 -->
      <el-tab-pane label="角色管理" name="roles">
        <div class="roles-management">
          <div class="toolbar">
            <el-button type="primary" @click="showAddRoleDialog">
              <i class="el-icon-plus"></i>
              添加角色
            </el-button>
          </div>

          <div class="roles-grid">
            <div
              v-for="role in roles"
              :key="role.id"
              class="role-card"
              :class="{ active: selectedRole?.id === role.id }"
              @click="selectRole(role)"
            >
              <div class="role-icon">
                <i :class="role.icon"></i>
              </div>
              <div class="role-info">
                <h3>{{ role.name }}</h3>
                <p>{{ role.description }}</p>
                <div class="role-stats">
                  <span class="stat-item">
                    <i class="el-icon-user"></i>
                    {{ role.userCount }} 用户
                  </span>
                  <span class="stat-item">
                    <i class="el-icon-key"></i>
                    {{ role.permissions.length }} 权限
                  </span>
                </div>
              </div>
              <div class="role-actions">
                <el-button type="text" @click.stop="editRole(role)">
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button type="text" @click.stop="deleteRole(role)" :disabled="role.id === 1">
                  <i class="el-icon-delete"></i>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 权限管理 -->
      <el-tab-pane label="权限管理" name="permissions">
        <div class="permissions-management">
          <div class="toolbar">
            <el-button type="primary" @click="showAddPermissionDialog">
              <i class="el-icon-plus"></i>
              添加权限
            </el-button>
          </div>

          <div class="permissions-tree">
            <el-tree
              :data="permissionsTree"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-expanded-keys="[1, 2, 3, 4]"
              class="permission-tree"
            >
              <template #default="{ data }">
                <div class="tree-node">
                  <div class="node-content">
                    <i :class="data.icon"></i>
                    <span>{{ data.name }}</span>
                    <el-tag size="small" type="info" v-if="data.code">{{ data.code }}</el-tag>
                  </div>
                  <div class="node-actions">
                    <el-button type="text" size="small" @click="editPermission(data)">
                      编辑
                    </el-button>
                    <el-button type="text" size="small" @click="deletePermission(data)">
                      删除
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-tab-pane>

      <!-- 权限分配 -->
      <el-tab-pane label="权限分配" name="assignment">
        <div class="permission-assignment">
          <div class="assignment-header">
            <div class="role-selector">
              <label>选择角色：</label>
              <el-select v-model="selectedRoleId" @change="handleRoleChange">
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </div>
            <div class="assignment-actions">
              <el-button type="primary" @click="saveRolePermissions">
                保存权限配置
              </el-button>
            </div>
          </div>

          <div class="assignment-content" v-if="selectedRole">
            <div class="role-info-card">
              <h3>{{ selectedRole.name }}</h3>
              <p>{{ selectedRole.description }}</p>
            </div>

            <div class="permissions-assignment">
              <el-tree
                :data="permissionsTree"
                :props="treeProps"
                show-checkbox
                node-key="id"
                ref="permissionTreeRef"
                :default-checked-keys="selectedRole.permissions"
                @check="handlePermissionCheck"
                class="assignment-tree"
              >
                <template #default="{ data }">
                  <div class="assignment-node">
                    <i :class="data.icon"></i>
                    <span>{{ data.name }}</span>
                    <el-tag size="small" type="info" v-if="data.code">{{ data.code }}</el-tag>
                  </div>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEditRoleMode ? '编辑角色' : '添加角色'"
      width="500px"
    >
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="角色图标" prop="icon">
          <el-select v-model="roleForm.icon" placeholder="请选择角色图标">
            <el-option label="管理员" value="el-icon-s-custom" />
            <el-option label="用户" value="el-icon-user" />
            <el-option label="编辑" value="el-icon-edit" />
            <el-option label="审核" value="el-icon-view" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roleForm.status" placeholder="请选择状态">
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="isEditPermissionMode ? '编辑权限' : '添加权限'"
      width="500px"
    >
      <el-form
        :model="permissionForm"
        :rules="permissionFormRules"
        ref="permissionFormRef"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-select v-model="permissionForm.parentId" placeholder="请选择父级权限">
            <el-option label="无" :value="null" />
            <el-option
              v-for="permission in flatPermissions"
              :key="permission.id"
              :label="permission.name"
              :value="permission.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="API" value="api" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限图标" prop="icon">
          <el-select v-model="permissionForm.icon" placeholder="请选择权限图标">
            <el-option label="首页" value="el-icon-s-home" />
            <el-option label="用户" value="el-icon-user" />
            <el-option label="设置" value="el-icon-setting" />
            <el-option label="数据" value="el-icon-data-analysis" />
            <el-option label="文档" value="el-icon-document" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'PermissionConfig',
  setup() {
    const activeTab = ref('roles')
    const selectedRole = ref(null)
    const selectedRoleId = ref(null)
    const roleDialogVisible = ref(false)
    const permissionDialogVisible = ref(false)
    const isEditRoleMode = ref(false)
    const isEditPermissionMode = ref(false)
    const roleFormRef = ref(null)
    const permissionFormRef = ref(null)
    const permissionTreeRef = ref(null)

    // 角色数据
    const roles = ref([
      {
        id: 1,
        name: '超级管理员',
        description: '拥有系统所有权限',
        icon: 'el-icon-s-custom',
        status: 'enabled',
        userCount: 1,
        permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
      },
      {
        id: 2,
        name: '管理员',
        description: '拥有系统管理权限',
        icon: 'el-icon-user',
        status: 'enabled',
        userCount: 5,
        permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      },
      {
        id: 3,
        name: '普通用户',
        description: '基础用户权限',
        icon: 'el-icon-user',
        status: 'enabled',
        userCount: 1242,
        permissions: [1, 2, 3, 4, 5]
      }
    ])

    // 权限树数据
    const permissionsTree = ref([
      {
        id: 1,
        name: '系统管理',
        icon: 'el-icon-setting',
        code: 'system',
        type: 'menu',
        parentId: null,
        children: [
          {
            id: 2,
            name: '用户管理',
            icon: 'el-icon-user',
            code: 'system:user',
            type: 'menu',
            parentId: 1
          },
          {
            id: 3,
            name: '权限配置',
            icon: 'el-icon-key',
            code: 'system:permission',
            type: 'menu',
            parentId: 1
          }
        ]
      },
      {
        id: 4,
        name: '内容管理',
        icon: 'el-icon-document',
        code: 'content',
        type: 'menu',
        parentId: null,
        children: [
          {
            id: 5,
            name: '谣言管理',
            icon: 'el-icon-warning',
            code: 'content:rumor',
            type: 'menu',
            parentId: 4
          },
          {
            id: 6,
            name: '案例管理',
            icon: 'el-icon-folder',
            code: 'content:case',
            type: 'menu',
            parentId: 4
          }
        ]
      },
      {
        id: 7,
        name: '模型管理',
        icon: 'el-icon-cpu',
        code: 'model',
        type: 'menu',
        parentId: null,
        children: [
          {
            id: 8,
            name: '训练监控',
            icon: 'el-icon-loading',
            code: 'model:training',
            type: 'menu',
            parentId: 7
          },
          {
            id: 9,
            name: '性能评估',
            icon: 'el-icon-data-line',
            code: 'model:evaluation',
            type: 'menu',
            parentId: 7
          }
        ]
      },
      {
        id: 10,
        name: '数据分析',
        icon: 'el-icon-data-analysis',
        code: 'data',
        type: 'menu',
        parentId: null,
        children: [
          {
            id: 11,
            name: '使用统计',
            icon: 'el-icon-pie-chart',
            code: 'data:statistics',
            type: 'menu',
            parentId: 10
          },
          {
            id: 12,
            name: '趋势分析',
            icon: 'el-icon-trend-charts',
            code: 'data:trend',
            type: 'menu',
            parentId: 10
          }
        ]
      }
    ])

    // 树形组件属性
    const treeProps = {
      children: 'children',
      label: 'name'
    }

    // 角色表单
    const roleForm = reactive({
      id: null,
      name: '',
      description: '',
      icon: '',
      status: 'enabled'
    })

    // 权限表单
    const permissionForm = reactive({
      id: null,
      name: '',
      code: '',
      parentId: null,
      type: 'menu',
      icon: ''
    })

    // 表单验证规则
    const roleFormRules = {
      name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
      description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
      icon: [{ required: true, message: '请选择角色图标', trigger: 'change' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    const permissionFormRules = {
      name: [{ required: true, message: '请输入权限名称', trigger: 'blur' }],
      code: [{ required: true, message: '请输入权限编码', trigger: 'blur' }],
      type: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
      icon: [{ required: true, message: '请选择权限图标', trigger: 'change' }]
    }

    // 扁平化权限数据
    const flatPermissions = computed(() => {
      const flatten = (permissions) => {
        let result = []
        permissions.forEach(permission => {
          result.push(permission)
          if (permission.children) {
            result = result.concat(flatten(permission.children))
          }
        })
        return result
      }
      return flatten(permissionsTree.value)
    })

    // 选择角色
    const selectRole = (role) => {
      selectedRole.value = role
      selectedRoleId.value = role.id
    }

    // 显示添加角色对话框
    const showAddRoleDialog = () => {
      isEditRoleMode.value = false
      resetRoleForm()
      roleDialogVisible.value = true
    }

    // 编辑角色
    const editRole = (role) => {
      isEditRoleMode.value = true
      Object.assign(roleForm, role)
      roleDialogVisible.value = true
    }

    // 删除角色
    const deleteRole = (role) => {
      ElMessageBox.confirm(`确定要删除角色 ${role.name} 吗？`)
        .then(() => {
          const index = roles.value.findIndex(r => r.id === role.id)
          if (index !== -1) {
            roles.value.splice(index, 1)
            ElMessage.success('角色删除成功')
          }
        })
        .catch(() => {})
    }

    // 重置角色表单
    const resetRoleForm = () => {
      Object.assign(roleForm, {
        id: null,
        name: '',
        description: '',
        icon: '',
        status: 'enabled'
      })
      if (roleFormRef.value) {
        roleFormRef.value.resetFields()
      }
    }

    // 保存角色
    const saveRole = () => {
      roleFormRef.value.validate((valid) => {
        if (valid) {
          if (isEditRoleMode.value) {
            // 编辑角色
            const index = roles.value.findIndex(r => r.id === roleForm.id)
            if (index !== -1) {
              roles.value[index] = { ...roleForm }
              ElMessage.success('角色更新成功')
            }
          } else {
            // 添加角色
            const newRole = {
              ...roleForm,
              id: Date.now(),
              userCount: 0,
              permissions: []
            }
            roles.value.push(newRole)
            ElMessage.success('角色添加成功')
          }
          roleDialogVisible.value = false
          resetRoleForm()
        }
      })
    }

    // 显示添加权限对话框
    const showAddPermissionDialog = () => {
      isEditPermissionMode.value = false
      resetPermissionForm()
      permissionDialogVisible.value = true
    }

    // 编辑权限
    const editPermission = (permission) => {
      isEditPermissionMode.value = true
      Object.assign(permissionForm, permission)
      permissionDialogVisible.value = true
    }

    // 删除权限
    const deletePermission = (permission) => {
      ElMessageBox.confirm(`确定要删除权限 ${permission.name} 吗？`)
        .then(() => {
          // 这里应该实现删除逻辑
          ElMessage.success('权限删除成功')
        })
        .catch(() => {})
    }

    // 重置权限表单
    const resetPermissionForm = () => {
      Object.assign(permissionForm, {
        id: null,
        name: '',
        code: '',
        parentId: null,
        type: 'menu',
        icon: ''
      })
      if (permissionFormRef.value) {
        permissionFormRef.value.resetFields()
      }
    }

    // 保存权限
    const savePermission = () => {
      permissionFormRef.value.validate((valid) => {
        if (valid) {
          // 这里应该实现保存逻辑
          ElMessage.success('权限保存成功')
          permissionDialogVisible.value = false
          resetPermissionForm()
        }
      })
    }

    // 处理角色变化
    const handleRoleChange = (roleId) => {
      const role = roles.value.find(r => r.id === roleId)
      if (role) {
        selectedRole.value = role
        // 设置树形控件的选中状态
        if (permissionTreeRef.value) {
          permissionTreeRef.value.setCheckedKeys(role.permissions)
        }
      }
    }

    // 处理权限勾选
    const handlePermissionCheck = (data, checked) => {
      if (selectedRole.value) {
        const checkedKeys = permissionTreeRef.value.getCheckedKeys()
        selectedRole.value.permissions = checkedKeys
      }
    }

    // 保存角色权限配置
    const saveRolePermissions = () => {
      if (!selectedRole.value) {
        ElMessage.warning('请选择角色')
        return
      }

      const checkedKeys = permissionTreeRef.value.getCheckedKeys()
      selectedRole.value.permissions = checkedKeys
      
      ElMessage.success('权限配置保存成功')
    }

    onMounted(() => {
      if (roles.value.length > 0) {
        selectRole(roles.value[0])
      }
    })

    return {
      activeTab,
      selectedRole,
      selectedRoleId,
      roleDialogVisible,
      permissionDialogVisible,
      isEditRoleMode,
      isEditPermissionMode,
      roleFormRef,
      permissionFormRef,
      permissionTreeRef,
      roles,
      permissionsTree,
      treeProps,
      roleForm,
      permissionForm,
      roleFormRules,
      permissionFormRules,
      flatPermissions,
      selectRole,
      showAddRoleDialog,
      editRole,
      deleteRole,
      resetRoleForm,
      saveRole,
      showAddPermissionDialog,
      editPermission,
      deletePermission,
      resetPermissionForm,
      savePermission,
      handleRoleChange,
      handlePermissionCheck,
      saveRolePermissions
    }
  }
}
</script>

<style scoped>
.permission-config {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #666;
}

.permission-tabs {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.role-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: flex-start;
  position: relative;
}

.role-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.role-card.active {
  border-color: #409eff;
  background: #f0f9ff;
}

.role-icon {
  width: 50px;
  height: 50px;
  background: linear-gradient(45deg, #409eff, #66d9ef);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24px;
  margin-right: 15px;
  flex-shrink: 0;
}

.role-info {
  flex: 1;
}

.role-info h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.role-info p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.role-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.stat-item i {
  margin-right: 5px;
}

.role-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 5px;
}

.permissions-tree {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 20px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-content i {
  font-size: 16px;
  color: #666;
}

.node-actions {
  display: flex;
  gap: 5px;
}

.assignment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.role-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

.role-selector label {
  font-weight: 500;
  color: #333;
}

.assignment-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 20px;
}

.role-info-card {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
  height: fit-content;
}

.role-info-card h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.role-info-card p {
  font-size: 14px;
  color: #666;
}

.permissions-assignment {
  background: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
}

.assignment-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.assignment-node i {
  font-size: 16px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .assignment-content {
    grid-template-columns: 1fr;
  }
  
  .assignment-header {
    flex-direction: column;
    gap: 15px;
  }
}
</style> 